<template>
  <div>
    <!-- <h1>用户页</h1> -->
    <div class="inp">
      <el-input
        v-model="input1"
        placeholder="请输入内容"
        class="input-with-select"
        clearable
        @input="input2"
      >
        <template #append>
          <el-button :icon="Search" @click="finduser" />
        </template>
      </el-input>
      <el-button type="primary" @click="dialogFormVisible = true"
        >添加用户</el-button
      >
      <el-dialog v-model="dialogFormVisible" title="添加用户">
        <el-form :model="form" :rules="rules">
          <el-form-item
            label="用户名"
            prop="username"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model="form.email" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="手机"
            prop="mobile"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.mobile" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogFormVisible = false), sesUser()"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogTableVisible" title="修改用户信息">
        <el-form :model="form" :rules="rules">
          <el-form-item
            label="用户名"
            prop="username"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form2.username"
              disabled
              placeholder="Please input"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model="form2.email" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="手机"
            prop="mobile"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form2.mobile" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogTableVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogTableVisible = false), getUser1()"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div class="cont">
      <div class="cont-top">
        <span class="cont-top-text1">#</span>
        <span class="cont-top-text2">姓名</span>
        <span class="cont-top-text2">邮箱</span>
        <span class="cont-top-text2">电话</span>
        <span class="cont-top-text2">角色</span>
        <span class="cont-top-text2">状态</span>
        <span class="cont-top-text2">操作</span>
      </div>
      <div
        class="cont-top"
        v-for="(item, index) in users.userlist"
        :key="index"
      >
        <span class="cont-top-text1">{{ index + 1 }}</span>
        <span class="cont-top-text2">{{ item.username }}</span>
        <span class="cont-top-text2">{{ item.email }}</span>
        <span class="cont-top-text2">{{ item.mobile }}</span>
        <span class="cont-top-text2">{{ item.role_name }}</span>
        <span class="cont-top-text2"
          >{{ item.mg_state }}
          <el-switch v-model="item.mg_state" @click="getTypes(item)" />
        </span>
        <span class="cont-top-text2">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="(dialogTableVisible = true), getUser(item)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="open(), delet1(item)"
          />
          <el-button
            type="warning"
            :icon="Star"
            circle
            @click="(outerVisible = true), getrole(item)"
          />
        </span>
      </div>
    </div>
    <!-- 分配角色 -->
    <el-dialog v-model="outerVisible" title="分配角色">
      <el-form :model="form">
        <el-form-item label="当前用户" :label-width="formLabelWidth">
          {{ form4.username }}
        </el-form-item>
        <el-form-item label="当前角色" :label-width="formLabelWidth">
          {{ form4.role_name }}
        </el-form-item>
        <el-form-item label="分配角色" :label-width="formLabelWidth">
          <el-select
            v-model="value"
            class="m-2"
            placeholder="请选择文章标签"
            size="large"
          >
            <el-option
              v-for="item in form4.roleList"
              :key="item.id"
              :label="item.label"
              :value="item.roleName"
              @click="roleRid(item.id)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="(outerVisible = false), getrole1()">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页器 -->
    <div class="demo-pagination-block" >
    <el-config-provider :locale="zhCn">
      <el-pagination
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[2, 5, 10, 15]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="users.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-config-provider>
    </div>
  </div>
</template>
<script setup>
import {
  getUsers,
  sesUsers,
  deleteUsers,
  getUserse,
  getType,
  findUsers,
  putUserRole,
  UserRoleList,
} from "../tools/ajax";
import { ref, reactive } from "vue";
import { Check, Edit, Delete, Search, Star } from "@element-plus/icons-vue";
import zhCn from 'element-plus/lib/locale/lang/zh-cn'  // 中文语言插件
import { ElMessage, ElMessageBox } from "element-plus";

const input1 = ref("");
const use = ref("false");
const users = reactive({});

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const currentPage4 = ref(1);
const pageSize4 = ref(5);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const outerVisible = ref(false);
const innerVisible = ref(false);

const value = ref("");
const rules = {
  // 表单验证规则
  username: [
    {
      required: true, // 必选项
      message: "请输入账号", // 验证失败提示
      trigger: "blur", // 失去焦点时验证
    },
    {
      min: 2, // 最少2个字符
      max: 6, // 最多6个字符
      message: "账号长度在2-6之间",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 4, // 最少4个字符
      max: 12, // 最多12个字符
      message: "密码长度在4-12之间",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      min: 4, // 最少4个字符
      max: 12, // 最多12个字符
      message: "邮箱长度在4-12之间",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
    {
      min: 4, // 最少4个字符
      max: 12, // 最多12个字符
      message: "手机号长度在4-12之间",
      trigger: "blur",
    },
  ],
};

// 选择每页几个
const handleSizeChange = (val) => {
  // console.log(`${val} items per page`);
  getUsers({ pagenum: currentPage4._value, pagesize: pageSize4._value }).then(
    (res) => {
      users.userlist = res.data.users;
    }
  );
};
// 选择第几页
const handleCurrentChange = (val) => {
  // console.log(`current page: ${val}`);
  getUsers({ pagenum: currentPage4._value, pagesize: pageSize4._value }).then(
    (res) => {
      users.userlist = res.data.users;
    }
  );
};
// 添加用户的弹窗数据
const form = reactive({
  username: "",
  password: "",
  email: "",
  mobile: "",
});
// 修改用户的弹窗数据
const form2 = reactive({
  id: "",
  username: "",
  email: "",
  mobile: "",
});

// 删除用户的数据
const form3 = reactive({
  id: "",
});

// 删除用户的弹窗
const open = () => {
  ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      delet();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
// 分配角色数据
const form4 = reactive({
  id: "",
  username: "",
  role_name: "",
  rid: "",
  roleList: "",
});
// 修改分配角色数据
function getrole(item) {
  form4.id = item.id;
  // form4.rid=item.rid
  form4.username = item.username;
  form4.role_name = item.role_name;
  // 分配角色列表
  UserRoleList().then((res) => {
    // console.log(res);
    form4.roleList = res.data;
  });
}
// 修改角色rid
function roleRid(id) {
  form4.rid = id;
}
// 分配角色
function getrole1() {
  putUserRole({ id: form4.id, rid: form4.rid }).then((res) => {
    // console.log(res);
    if (res.meta.status == 200) {
      ElMessage.success(res.meta.msg);
      getUserList();
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
}
// 请求用户列表
function getUserList() {
  getUsers({ pagenum: currentPage4._value, pagesize: pageSize4._value }).then((res) => {
    // users.push(...res.data.users);
    console.log(res);
    users.userlist = res.data.users;
    users.total=res.data.total
  });
}
getUserList();
// 查找用户
function finduser() {
  console.log(input1._rawValue);
  findUsers({ id: input1._rawValue * 1 }).then((res) => {
    // console.log(res);
    users.userlist=[]
    users.userlist.push(res.data);
  });
}
// 输入框为空时重新调用
function input2() {
  if (input1._value == "") {
    getUserList();
  }
}
// 传入删除id
function delet1(item) {
  form3.id = item.id;
}
// 删除用户
function delet() {
  deleteUsers({ id: form3.id }).then((res) => {
    // console.log(res);
    if (res.meta.status == 200) {
      ElMessage.success(res.meta.msg);
      getUserList();
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
  // console.log(item.id);
}
//修改用户状态
function getTypes(item) {
  // console.log(item);
  getType({ uId: item.id, type: item.mg_state }).then((res) => {
    ElMessage.success(res.meta.msg);
  });
}
// 添加用户
function sesUser() {
  sesUsers(form).then((res) => {
    // console.log(res);
    if (res.meta.status == 201) {
      ElMessage.success(res.meta.msg);
      getUserList();
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
}
// 修改用户信息
function getUser1() {
  getUserse({ id: form2.id, email: form2.email, mobile: form2.mobile }).then(
    (res) => {
      // console.log(res);
      getUserList();
    }
  );
}
// 给from2传值
function getUser(item) {
  (form2.id = item.id), (form2.username = item.username);
  form2.email = item.email;
  form2.mobile = item.mobile;
}
</script>
<style scoped lang="less">
.inp {
  width: 500px;
  display: flex;
}
.input-with-select {
  margin-right: 50px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.cont-top {
  display: flex;
  justify-content: space-between;
  text-align: left;
  color: gray;
  line-height: 50px;
  .cont-top-text1 {
    width: 50px;
    height: 50px;
  }
  .cont-top-text2 {
    width: 180px;
    height: 50px;
  }
}
</style>